package  ${cfg.package_dir}.${cfg.cfgName};
import com.ChatMessage;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMqConf{

    @Autowired
    AmqpAdmin amqpAdmin;

    public static final String EX_WEBSOCKET = "aj.websocket ";
    public static final String WS_QUEUE_1 = "aj.ws.queue_1";
    public static final String WS_QUEUE_2 = "aj.ws.queue_2";

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        // json序列化
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        // 相关数据：correlationData     确认情况：ack    原因：cause
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println(ack);
        });
        // 消息：message   回应码：replyCode)    回应信息：replyText    交换机：exchange    路由键：routingKey
        rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey)->{
            System.out.println(message);
        });
        return rabbitTemplate;
    }


    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        Jackson2JsonMessageConverter jsonConverter = new Jackson2JsonMessageConverter();
        jsonConverter.setClassMapper(classMapper());
        return jsonConverter;
    }

    @Bean
    public DefaultClassMapper classMapper() {
        DefaultClassMapper classMapper = new DefaultClassMapper();
        Map<String, Class<?>> idClassMapping = new HashMap<>();
        idClassMapping.put("chat", ChatMessage.class);
        //idClassMapping.put("thing2", Thing2.class);
        classMapper.setIdClassMapping(idClassMapping);
        return classMapper;
    }

    @PostConstruct
    public void init(){
        amqpAdmin.declareExchange(new TopicExchange(EX_WEBSOCKET,true,false));
        amqpAdmin.declareQueue(new Queue(WS_QUEUE_1,true,false,false));
        amqpAdmin.declareQueue(new Queue(WS_QUEUE_2,true,false,false));
        amqpAdmin.declareBinding(new Binding(WS_QUEUE_1, Binding.DestinationType.QUEUE,EX_WEBSOCKET,"ws1",null));
        amqpAdmin.declareBinding(new Binding(WS_QUEUE_2, Binding.DestinationType.QUEUE,EX_WEBSOCKET,"ws2",null));
    }

}
